module top_module(
    input clk,
    input [7:0] in,
    input reset,    // Synchronous reset
    output [23:0] out_bytes,
    output done); //

    // FSM from fsm_ps2
	parameter IDLE = 2'b00;
    parameter FIRST = 2'b01;
    parameter SECOND = 2'b10;
    parameter THIRD = 2'b11;
    
    reg	[1:0]	state;
    reg	[1:0]	next_state;
    
    reg	[23:0]	out_reg;
    
    // State transition logic (combinational)
    always @(*) begin
        case(state)
            IDLE:begin
                if(in[3]) begin
                    next_state = FIRST;
                    out_reg = {in, out_reg[15:0]};
                end
                else begin
                    next_state = IDLE;
                    out_reg = 24'd0;
                end
            end
            FIRST:begin
                next_state = SECOND;
                out_reg = {out_reg[23:16] ,in, out_reg[7:0]};
            end
            SECOND:begin
                next_state = THIRD;
                out_reg = {out_reg[23:8], in};
            end
            THIRD:begin
                if(in[3]) begin
                    next_state = FIRST;
                    out_reg = {in, out_reg[15:0]};
                end
                else begin
                    next_state = IDLE;
                    out_reg = 24'd0;
                end
            end
        endcase
    end
    
    // State flip-flops (sequential)
    always @(posedge clk) begin
        if(reset) begin
            state <= IDLE;
            out_bytes <= 24'd0;
        end
        else begin
            state <= next_state;
            out_bytes <= out_reg;
        end
    end
    
    // Output logic
    assign done = (state == THIRD);
    
    // New: Datapath to store incoming bytes.

endmodule
